package helpers;

import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class DataStoreHelper {

	public static String getKeyFileName(String filename) {

		String cachePrefix="datastore_";
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e1) {
		   e1.printStackTrace();
		}
		if(cache!=null&&cache.containsKey(cachePrefix+filename))
		{
			return (String)cache.get(cachePrefix+filename)	;
		}
		Query query = new Query("__BlobInfo__");

		query.addFilter("filename", FilterOperator.EQUAL, filename);
		query.setKeysOnly();
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		PreparedQuery pq = datastore.prepare(query);
		List<Entity> entList = pq.asList(FetchOptions.Builder.withLimit(1));
		if (entList.size() == 0) {
			return null;
		} else {
			String key =  entList.get(0).getKey().getName();
			if(cache!=null)
			{
				cache.put(cachePrefix+filename, key);
			}
			return key;
		}
		
		

	}
}
